<?php

// Created by Khanh Nam
/*
 * This controller is used to response common ajax request
 */
class AjaxController extends Controller{
    public $layout='//layout/column1';
    
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            array(
                'application.filters.RequireLoginFilter',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'users' => array('@'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }
    
    /*
     * Filter check login
     */
    public function filterCheckLogin($filterChain){
        if(Yii::app()->user->isGuest){
            Yii::app()->end();
        }
        $filterChain->run();
    }
    public function actionSearchCustomer($term){
        
        if(strlen($term)<3){
            return;
        }
        
        $customerList=Yii::app()->db->createCommand('select custno, lastname from tbl_customers where custno like :query or lastname like :query')
                ->bindValue('query', "%$term%")->queryAll();
        $rs=array();
        foreach($customerList as $customer){
            $rs[]=array(
                'value'=>$customer['custno'],
                'label'=>$customer['custno'].' - '.$customer['lastname']
            );
        }
        echo CJSON::encode($rs);
        
    }
    public function actionSearchCity($term){
        
        if(strlen($term)<=3) return "[]";
        $data=Yii::app()->db->createCommand('select distinct city,state,zipcode,county from tbl_taxcode where city like :city')->bindValue('city',"%$term%")->queryAll();
        $rs=array();
        foreach($data as $i=>$item){
            $rs[$i]['value']=$item['city'];
            $rs[$i]['label']=$item['city'].', '.$item['state'].' '.$item['zipcode'];
            
        }
        echo json_encode($rs);
    }
    public function actionLookupCounty($zipcode=NULL){
        if(strlen($zipcode)>5){
            $zipcode=substr($zipcode,0,5);
        }
        $row=Yii::app()->db->createCommand('select county from tbl_taxcode where zipcode like :zipcode')->bindValue('zipcode', $zipcode)->queryScalar();
        if($row!=NULL){
            echo $row;
        }
        echo '';
    }
    public function actionGetCityData($term=NULL){
        $data=Yii::app()->db->createCommand('select city,state,zipcode,county from tbl_taxcode where city like :city')->bindValue('city',"$term")->queryRow();
        $rs=array();
        if($data==NULL) return;
   
        
            $rs['city']=$data['city'];
            $rs['state']=$data['state'];
            $rs['zipcode']=$data['zipcode'];
           
      
        echo json_encode($rs);
    }
    public function actionGetLocationList($custno){
        $list=Yii::app()->db->createCommand('select * from tbl_locations where custno=:custno')->bindValue('custno', $custno)->queryAll();
        $rs=array(
            NULL=>'N/A'
        );

        foreach($list as $i=>$item){
            $rs[$item['locno']]=$item['locno'].' - '.$item['locname'].' | '.$item['add1'].' | '.$item['city'].' | '.$item['state'];
            
        }
        
        echo json_encode($rs);
    }
    public function actionGetJobList($custno,$locno){
        $rs=Jobs::getJobByLocation($custno,$locno);
        echo json_encode($rs);
    }
    /*
     * General search function, return json array
     * Only accept ajax request
     * Now we just search customer
     */
    public function actionSearch($query=NULL,$page=1,$sort='',$dir=''){
       
        header('Content-Type:text/javascript');
        $query=trim($query);
        //if query is a location custno-locno
        $match=null;
        if(preg_match('/(\d{7})-(\d{5})/', $query,$match)==1){
            $custno=$match[1];
            $locno=$match[2];
            $location=Locations::model()->find('custno=:custno AND locno=:locno',array(
                'custno'=>$custno,
                'locno'=>$locno,
            ));
            if($location!=NULL){
                $data=array();
                
                $rs=array(
                    'totalCount'=>1,
                  
                    'data'=>array(
                        'id'=>$location->id,
                        'link'=>"index.php?r=locations/update&id=$location->id",
                        'title'=>"$location->locname ($location->custno-$location->locno)",
                        'type'=>'Locations'
                    )
                );
                echo json_encode($rs);
            }
            
        }else{
            //$offset=($page-*20
            $sql="select distinct 
                'customer' as type,
                null as col1, 
                custno as col2,
                null as col3,
                lastname as col4,
                firstname as col5, 
                add1 as col6,
                add2 as col7 
                from tbl_customers 
                where custno=:custno or firstname like :query or lastname like :query or add1 like :query or add2 like :query
                
                union all select 
                'location' as type,
                id as col1,
                custno as col2,
                locno as col3, 
                null as col4,
                locname as col5, 
                add1 as col6, 
                add2 as col7 
                from tbl_locations
                where add1 like :query or add2 like :query
                
                union all select
                'inventory' as type,
                partno as col1,
                mfg as col2,
                description as col3,
                null as col4,
                model as col5,
                null as col6,
                null as col7
				from tbl_inventory
                where partno like :query or mfg like :query or model like :query
            
                ";
            $count=Yii::app()->db->createCommand("
                select count(*) from ($sql) sq
                ")->queryScalar(array(
                    'custno'=>$query,
                    'query'=>"%$query%",
                ));
            
            $data=new CSqlDataProvider($sql,array(
                'params'=>array(
                    'custno'=>$query,
                    'query'=>"%$query%",
                ),
                'totalItemCount'=>$count,
                'pagination'=>array(
                    'pageSize'=>20,
                    'currentPage'=>$page
                )
            ));
           
            $rs=array();
            $rs['totalCount']=$count;
            
            foreach($data->getData() as $item){
                //because we search both in customer and location
                //if result dont have locno or locno==NULL then item is customer
                if($item['type']=='customer'){
                    $link='index.php?r=customers/update&id='.$item['col2'];
                    $title=$item['col5'].' '.$item['col4']."({$item['col2']})";
                    $type='Customers';
                    
                }else if($item['type']=='locations'){
                    $link='index.php?r=locations/update&id='.$item['col1'];
                    $title="{$item['col5']} ({$item['col2']}-{$item['col3']})";
                    $type='Locations';
                }else if($item['type']=='inventory'){
                    $link='index.php?r=inventory/update&id='.$item['col1'];
                    $title="{$item['col2']}-{$item['col4']}-{$item['col5']} ({$item['col1']})";
                    $type='Inventory';
                }
                $rs['data'][]=array(
                    
                    'title'=>$title,
                    'link'=>$link,
                    'type'=>$type,
                );
            }
            echo json_encode($rs);
        }
      
    }
    
    public function actionEntitySearch($entityId, $entityName) {
    	$user = Users::model()->findByPk(Yii::app()->user->getId());
                    $empno = $user->employeeid;
    	$url = "";
    	$success = true;
    	$errorMsg = "";
    	switch($entityName) {
    		case "invoices":
    			$model = Invoice::model()->findByPk($entityId);
    			if ($model == NULL) {
    				$success = false;
    				$errorMsg = "The Invoice/Sales Order/Quotation:\"$entityId\" was not found, please try again";
    			} else {
					if($model->salesperson!=  $empno){
						$success = false;
    				$errorMsg = "
    				 Another sales person has been assigned to this  Invoice/Sales Order/Quotation. 
    				  If you believe this is an error, please contact your System Administrator.";
						}
    				$url = Yii::app()->createAbsoluteUrl('salespersonportal/invoices/update', array('invoice' => $entityId));
    			}
    			break;
    		case "contract":
    			$model = Contracts::model()->findByPk($entityId);
    			if ($model == NULL) {
    				$success = false;
    				$errorMsg = "The Contract:\"$entityId\" was not found, please try again";
    			} else {
					if($model->salesperson!=  $empno){
						$success = false;
    				$errorMsg = "
    				 Another sales person has been assigned to this Contract. 
    				  If you believe this is an error, please contact your System Administrator.";
						}
    				$url = Yii::app()->createAbsoluteUrl('salespersonportal/contracts/update', array('contractid' => $entityId));
    			}
    			break;
    		case "job":
    			$model = Jobs::model()->findByPk($entityId);
    			if ($model == NULL) {
    				$success = false;
    				$errorMsg = "The Job:\"$entityId\" was not found, please try again";
    			} else {
						if($model->jobsalesperson!=  $empno){
						$success = false;
    				$errorMsg = "
    				 Another sales person has been assigned to this Job. 
    				  If you believe this is an error, please contact your System Administrator.";
						}
    				$url = Yii::app()->createAbsoluteUrl('salespersonportal/jobs/update', array('jobid' => $entityId));
    			}
    			break;
    		default:
    			$success = false;
    			$errorMsg = "Please select proper search entity.";
    	}
    	$ret = array(
    		"url" => $url,
    		"success" => $success,
    		"errorMsg" => $errorMsg
    	);
    	echo json_encode($ret);
    }
    
    public function actionLoadPageInAjax($url){
        assert('is_string($url)');
      
        $this->layout = '//layout/space';
        $this->render('loadPageInAjax',array(
            'url'=>$url,
            
        ));
    }
}
?>
